﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PreeRegisterModel;
using System.Configuration;
using PreeRegisterDAL;
using System.Data;

namespace PreeRegisterBLL.Security
{
    public class ResultDecode
    {

        /// <summary>
        /// 获取头信息
        /// </summary>
        /// <returns></returns>
        public static Head GetHead()
        {
            try
            {
                string TimeStamp = timestamp.GetTimeStamp(false);
                //string Fromtype = "wd1cx80ad3hj";
                //string Encryptkey = "77A7BB1D28A5EAC6076D61388C51904B";
                string Encryptkey = ConfigurationManager.AppSettings["k101"].ToString();
                string Fromtype = ConfigurationManager.AppSettings["k102"].ToString();

                Head myhead = new Head();
                myhead.token = Caltoken.GetToken(Encryptkey, Fromtype, TimeStamp);
                myhead.version = "1.0";
                myhead.fromtype = Fromtype;
                myhead.sessionid = Guid.NewGuid().ToString();
                myhead.time = TimeStamp;
                return myhead;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取头信息_简单
        /// </summary>
        /// <returns></returns>
        public static Head_Sample GetHead_Sample()
        {
            try
            {
                string Encryptkey = ConfigurationManager.AppSettings["k101"].ToString();
                string TimeStamp = timestamp.GetTimeStamp(false);

                Head_Sample myhead = new Head_Sample();
                myhead.token = Caltoken.GetToken_Sample(Encryptkey, TimeStamp);
                myhead.time = TimeStamp;
                return myhead;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 反序列化jsonData请求字符串，并解密头和内容，校验合法性  
        /// </summary>
        /// <param name="ResponseJson"></param>
        /// <returns></returns>
        public static bool DecodeResult(string Json, string Method, ref string head_json, ref string body_json, ref string ErrMsg)
        {
            try
            {
                //反序列化jsonData请求字符串
                EncodeModel EncodeModel = csSerialize.EncodeDeSerialize(Json);

                //解密头和内容信息
                if (EncodeModel.head.Contains("%"))
                    head_json = System.Web.HttpUtility.UrlDecode(EncodeModel.head);//add by zhuyr
                head_json = Base64.DecodeBase64(EncodeModel.head);

                //改为url解码，默认为utf-8字符集，其它编码走重载方法  liujia160103
                //string body_json_temp = System.Web.HttpUtility.UrlEncode(EncodeModel.body);

                //body_json_temp = System.Web.HttpUtility.UrlDecode(body_json_temp);

                // string body_json_temp = EncodeModel.body.Replace("%2B", "+");   
                string body_json_temp = EncodeModel.body;
                
                if (EncodeModel.body.Contains("%"))
                    body_json_temp = System.Web.HttpUtility.UrlDecode(EncodeModel.body);//add by zhuyr

                body_json = Base64.DecodeBase64(body_json_temp);

                //liujia  区分联康与非联康加密方式
                bool bContainVersion = head_json.Contains("version");

                if (bContainVersion)
                {
                    VariableBLL.EncryptType = 1;

                    Head head = csSerialize.RequestHeadInfo(head_json);

                    string fromtype_local = ConfigurationManager.AppSettings["k102"].ToString();

                    if (head.fromtype != fromtype_local)
                    {
                        ErrMsg = "头信息校验失败：来源标识非法！";
                        return false;
                    }

                    string Encryptkey = ConfigurationManager.AppSettings["k101"].ToString();
                    string token_local = Caltoken.GetToken(Encryptkey, fromtype_local, head.time);
                    if (head.token != token_local)
                    {
                        ErrMsg = "头信息校验失败：token非法！";
                        return false;
                    }
                }
                else
                {
                    VariableBLL.EncryptType = 2;

                    return VerifyToken(head_json, Method, ref ErrMsg);
                }

                return true;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 序列化加密的返回结果信息
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public static EncodeModel EncodeResult(string body)
        {
            try
            {
                //加密内容信息
                string JSON_Encode = Security.Base64.EncodeBase64(body);

                //特殊字符替换
                JSON_Encode = System.Web.HttpUtility.UrlEncode(JSON_Encode); 

                //构造加密返回结果类
                EncodeModel encodeModel = new PreeRegisterModel.EncodeModel();
                if (VariableBLL.EncryptType == 1)
                {
                    encodeModel.head = csSerialize.Head();
                }
                else
                {
                    encodeModel.head = csSerialize.Head_Sample();
                }
                encodeModel.body = JSON_Encode;

                //返回序列化返回结果
                //return csSerialize.ResponseInfo(encodeModel);
                return encodeModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        public static EncodeModel EncodeResult2(string body)
        {
            try
            {
                //构造加密返回结果类
                EncodeModel encodeModel = new PreeRegisterModel.EncodeModel();
                if (VariableBLL.EncryptType == 1)
                {
                    encodeModel.head = csSerialize.Head();
                }
                else
                {
                    encodeModel.head = csSerialize.Head_Sample();
                }
                encodeModel.body = body;

                //返回序列化返回结果
                //return csSerialize.ResponseInfo(encodeModel);
                return encodeModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 校验token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool VerifyToken(string head_json, string Method, ref string ErrMsg)
        {
            try
            {
                //string Encryptkey = ConfigurationManager.AppSettings["k101"].ToString();
                //string token_local = Caltoken.GetToken_Sample(Encryptkey);
                //if (token != token_local)
                //{
                //    return false;
                //}
                //return true;

                //解析头信息
                Head_Sample head = csSerialize.RequestHeadInfo_Sample(head_json);
                string FromType = head.fromtype;
                string timestamp = head.time;
                string token = head.token;

                //查询厂商密钥及接口访问权限
                DataSet ds = RightVerifyDAL.GetFromTypeRight(FromType);

                //校验厂商注册信息
                if (ds == null || ds.Tables.Count < 2 || ds.Tables[0].Rows.Count == 0)
                {
                    ErrMsg = "头信息校验失败：无此接入商注册信息！";
                    return false;
                }

                //校验厂商密钥信息
                string securityKey = ds.Tables[0].Rows[0]["securityKey"].ToString();
                string token_local = Caltoken.GetToken_Sample(securityKey, timestamp);
                if (token != token_local)
                {
                    ErrMsg = "头信息校验失败：token非法！";
                    return false;
                }

                //校验厂商接口访问权限
                DataView dvRight = ds.Tables[1].DefaultView;
                dvRight.RowFilter = "MethodName='" + Method + "'";
                if (dvRight.Count < 1)
                {
                    ErrMsg = "头信息校验失败：该厂商没有此接口访问权限！";
                    return false;
                }

                return true;
            }
            catch (Exception err)
            {

                throw err;
            }
        }
    }
}
